package com.afdor.rws.event.driven.channel.local.consumer.retry;

import com.afdor.rws.annotation.extension.Extension;
import com.afdor.rws.event.driven.channel.consumer.handler.EventRetryStrategy;
import com.afdor.rws.event.driven.channel.local.observer.ObserverEvent;
import com.afdor.rws.event.driven.channel.local.observer.ObserverEventSource;
import com.afdor.rws.event.driven.entities.Event;
import lombok.Getter;
import lombok.NonNull;

import java.util.Optional;

/**
 * 默认重试策略，即重试次数加1，并保存，未做真正的重试处理
 *
 * @author 悭梵
 * @date Created in 2018-08-21 15:30
 */
@Extension(value = "local", order = Extension.NORMAL_ORDER - 100, interfaceClass = EventRetryStrategy.class)
public class LocalEventRetryStrategy implements EventRetryStrategy<ObserverEvent> {

    private int maxRetryCount = 6;


    @Getter
    private ObserverEventSource eventSource;

    public LocalEventRetryStrategy(ObserverEventSource eventSource) {
        super();
        setEventSource(eventSource);
    }

    public void setEventSource(ObserverEventSource eventSource) {
        this.eventSource = Optional.ofNullable(eventSource).orElseThrow(() -> new IllegalArgumentException("事件管理容器为空"));
    }

    @Override
    public boolean allowRetry(@NonNull ObserverEvent observerEvent) {
        return observerEvent.getEvent() != null && observerEvent.getEvent().getRetryCount() < getMaxRetryCount();
    }

    @Override
    public void retry(@NonNull ObserverEvent observerEvent) {
        Event event = observerEvent.getEvent();
        if (event != null) {
            event.addRetry();
            eventSource.asyncSendEvent(observerEvent);
        }
    }

    public int getMaxRetryCount() {
        return maxRetryCount;
    }
}
